-- Export in tileset format

function main ()
 local w = mappy.getValue(mappy.MAPWIDTH)
 local h = mappy.getValue(mappy.MAPHEIGHT)

 if (w == 0) then
  mappy.msgBox ("Export binary file", "You need to load or create a map first", mappy.MMB_OK, mappy.MMB_ICONINFO)
 else
  local isok,asname = mappy.fileRequester (".", "Tileset files (*.map)", "*.map", mappy.MMB_SAVE)
  if isok == mappy.MMB_OK then
   if (not (string.sub (string.lower (asname), -4) == ".map")) then
    asname = asname .. ".map"
   end
   adjust = -1
-- open file as text
   outas = io.open (asname, "w")
   outas:write (w)
   outas:write ("\n")
   outas:write (h)
   outas:write ("\n")
   local y = 0
   while y < h do
    local x = 0
    while x < w do
     local mapval = mappy.getBlockValue (mappy.getBlock (x, y), mappy.BLKBG)
     mapval = mapval + adjust
     if mapval < 0 then
      mapval = 0
     end
     outas:write(mapval)
     outas:write(",")
     x = x + 1
    end
    y = y + 1
   end
   outas:close ()
   end
  end
end

test, errormsg = pcall( main )
if not test then
    mappy.msgBox("Error ...", errormsg, mappy.MMB_OK, mappy.MMB_ICONEXCLAMATION)
end
